<!--
 @description 新建经销商档案变更
 @fileName Add.vue
 @author zengqiongying
 @created 2023/04/18 20:46:23
-->
<template>
  <div class="has-foot-pb">
    <Card no-mg :round="false">
      <Cell :modelValue="formData.officeName" title="办事处" placeholder="选择办事处" @right="onSearchOffice" />
      <template v-if="!!formData.officeCode">
        <Cell :modelValue="formData.officeCode" title="办事处编码" readonly />
        <Cell :modelValue="formData.officeTypeName" title="办事处类别" readonly />
        <!-- <Cell :modelValue="formData.personName" title="办事处负责人" readonly /> -->
      </template>

      <FieldSelect
        v-model="formData.isOtherReceiveManagerKnow"
        title="是否需要其他业务客户经理接收知晓"
        :url="`/data-dict/app/v2/dictionary/BOOLEANS`"
        label-name="dictName"
        value-name="dictCode"
        method="get"
        :params="dictParams"
        required
      />
      <template v-if="[1, '1'].includes(formData.isOtherReceiveManagerKnow)">
        <Cell
          v-if="formData.officeCode"
          :modelValue="formData.receiveManagerName"
          title="接收客户经理"
          placeholder="选择客户经理"
          :required="['1', 1].includes(formData.isOtherReceiveManagerKnow)"
          @right="onSearchCustomerManager"
        />

        <template v-if="!!formData.receiveManagerCode">
          <Cell :modelValue="formData.receiveManagerCode" title="接收客户经理编码" readonly />
          <Cell :modelValue="formData.receiveManagerTypeName" title="接收客户经理类型" readonly />
          <Cell :modelValue="formData.receiveManagerTel" title="接收客户经理电话" readonly />
        </template>
      </template>
      <Cell title="提报意见" is-column custom :right="false">
        <qmp-field v-model="formData.submitAnOpinion" type="textarea" placeholder="输入内容" class="ctm-text-area" />
      </Cell>
    </Card>

    <Card no-mg :round="false">
      <Cell
        v-model="formData.customerName"
        title="经销商系统名称"
        placeholder="请输入"
        :maxlength="50"
        :right="false"
        is-input
        required
        inputAlign="right"
      />
      <Cell
        v-model="formData.legalPerson"
        title="经销商姓名"
        placeholder="请输入"
        :maxlength="50"
        :right="false"
        is-input
        required
        inputAlign="right"
      />
      <Cell
        v-model="formData.credentialNo"
        title="经销商身份证号"
        placeholder="请输入"
        :maxlength="50"
        :right="false"
        is-input
        required
        type="tel"
        inputAlign="right"
      />
      <!-- <Cell
        v-model="formData.disAddr"
        title="身份证详细地址"
        placeholder="请输入"
        :maxlength="50"
        :right="false"
        is-input
        required
        inputAlign="right"
      /> -->
      <FieldDateTime
        v-model="formData.cooperateStart"
        title="合作起始日期"
        placeholder="选择合作日期"
        type="date"
        :default-date="formData.cooperateStart"
        :max-date="maxDate"
        :min-date="minDate"
        clear
        required
      />
    </Card>

    <div :class="['ctm-content-foot', { relative: keyboard.show }]">
      <div class="btn radius-larg ctm-btn-main" @click="onCreate">下一步</div>
    </div>
  </div>
</template>

<script lang="ts">
  import { reactive, toRefs, getCurrentInstance } from 'vue'
  import { useRouter, onBeforeRouteLeave } from 'vue-router'
  import { useStore } from 'vuex'
  import Card from '@/components/Card/index.vue'
  import FieldSelect from '@/components/FieldSelect/index.vue'
  import Cell from '@/components/Cell/index.vue'
  import FieldDateTime from '@/components/FieldDateTime/index.vue'
  import { createSaveBasic } from '@/apis/dealerMarketing/NewArchive'
  import GetKeyboardMixin from '@/utils/useKeyboard'
  import { validIDCard } from '@/utils/validate'

  interface anyObjectModle {
    [key: string]: any
  }
  export default {
    name: 'DealerNewArchiveAdd',
    components: { Card, FieldSelect, Cell, FieldDateTime },
    setup() {
      const instance = getCurrentInstance()
      const { proxy }: any = instance
      const $store = useStore()
      const $router = useRouter()
      const datas = reactive<anyObjectModle>({
        isSave: false, //是否已保存
        dictParams: { query: { appCode: 'slm', domainCode: 'marketing' }, type: 0 },
        maxDate: new Date(),
        minDate: new Date(),
        formData: {
          officeCode: '',
          officeName: '',
          officeTypeCode: '',
          officeTypeName: '', // 办事处类别
          personName: '', //办事处负责人
          personCode: '', //办事处责任编码

          isOtherReceiveManagerKnow: '0', //是否需要其他业务客户经理接收知晓
          receiveManagerCode: '', // 接收经理
          receiveManagerName: '',
          receiveManagerTel: '',
          receiveManagerTypeName: '',
          receiveManagerTypeCode: '',
          submitAnOpinion: '', //提报意见

          customerName: '',
          legalPerson: '',
          credentialNo: '',
          disAddr: '',
          cooperateStart: ''
        }
      })
      datas.keyboard = {
        show: false
      }
      datas.keyboard = GetKeyboardMixin()
      const onSearchOffice = () => {
        proxy.$SimpleEvents.registerEvent('NewArchiveAddSetOffice', (data: any) => {
          onChangeOffice(data)
        })
        $router.push({
          path: '/search/Office',
          query: {
            name: 'NewArchiveAddSetOffice'
          }
        })
      }
      const onSearchCustomerManager = () => {
        const officeCode = datas.formData.officeCode
        if ([undefined, null, ''].includes(officeCode)) {
          proxy.$toast('请先选择办事处')
          return
        }
        proxy.$SimpleEvents.registerEvent('NewArchiveAddSetManager', (data: any) => {
          onChangeReceiveManager(data)
        })
        $router.push({
          path: '/search/personManager',
          query: {
            name: 'NewArchiveAddSetManager',
            office: officeCode
          }
        })
      }

      const onChangeOffice = (d: any) => {
        const officeData = {
          officeCode: d?.code || '',
          officeName: d?.name || '',
          officeTypeCode: d?.officeTypeCode || '',
          officeTypeName: d?.officeTypeName || '',
          personCode: d?.principalCode || '',
          personName: d.principalName || ''
        }
        datas.formData = { ...datas.formData, ...officeData }
      }
      const onChangeReceiveManager = (d: any) => {
        const receiveManager = {
          receiveManagerCode: d?.personCode || '',
          receiveManagerName: d?.personName || '',
          receiveManagerTel: d?.personTel || '',
          receiveManagerTypeCode: d?.accountType || '',
          receiveManagerTypeName: d?.accountTypeName || ''
        }
        datas.formData = { ...datas.formData, ...receiveManager }
      }
      const onCreate = () => {
        const d = { ...datas.formData }
        if (!d.officeCode) {
          proxy.$toast('请选择办事处')
          return
        }
        if (!d.isOtherReceiveManagerKnow) {
          proxy.$toast('请选择是否需要其他业务客户经理接收知晓')
          return
        }
        if (['1', 1].includes(d.isOtherReceiveManagerKnow) && !d.receiveManagerCode) {
          proxy.$toast('请选择接收客户经理')
          return
        }
        if (!d.customerName) {
          proxy.$toast('请输入经销商名称')
          return
        }
        if (!d.legalPerson) {
          proxy.$toast('请输入经销商姓名')
          return
        }
        if (!d.credentialNo) {
          proxy.$toast('请输入经销商身份证号')
          return
        }

        if (!validIDCard(d.credentialNo)) {
          proxy.$toast('经销商身份证号码无效')
          return
        }
        /* if (!d.disAddr) {
          proxy.$toast('请输入身份证详细地址')
          return
        } */
        proxy.$dialog.confirm({
          title: '保存新建',
          message: '保存当前经销商档案',
          lockScroll: true,
          confirmButtonText: '保存并继续填写',
          cancelButtonText: '保存并返回',
          closeOnClickOverlay: false,
          beforeClose: (action: any) => {
            return new Promise((resolve) => {
              if (!action) {
                resolve(true)
                return
              }
              setTimeout(() => {
                if (action === 'confirm') {
                  saveFormData(
                    (id: string) => {
                      // 保存进入编辑
                      $router.replace({
                        path: '/dealerNewArchive/edit',
                        query: {
                          id
                        }
                      })
                      resolve(true)
                    },
                    () => {
                      resolve(true)
                    }
                  )
                } else if (action === 'cancel') {
                  // 保存并返回
                  saveFormData(
                    (id: string) => {
                      // 保存进入编辑
                      datas.isSave = true
                      $router.goBack()
                      resolve(true)
                    },
                    () => {
                      resolve(true)
                    }
                  )
                }
              }, 1000)
            })
          }
        })
      }

      const saveFormData = (callback: any, closeback: any) => {
        const data = {
          ...datas.formData,
          ...{ schedule: 'A' }
        }
        if (datas.formData.cooperateStart) {
          data.cooperateStart = `${datas.formData.cooperateStart} 00:00:00`
        }
        createSaveBasic(data)
          .then((res: any) => {
            if (res.success === 1) {
              proxy.$SimpleEvents.emit('refreshCustomerChangeList')
            } else {
              proxy.$toast('经销商创建失败')
            }
            callback && callback(res?.msg)
            closeback && closeback()
          })
          .catch(() => {
            closeback && closeback()
          })
      }

      onBeforeRouteLeave((to, from, next) => {
        const instanceName = instance?.type?.name
        const toName: any = to.name
        if (['DealerInfoNewArchive', 'DealerNewArchiveEdit'].includes(toName)) {
          $store.commit('routerKeep/removeCache', instanceName)
        } else {
          $store.commit('routerKeep/resetCache', instanceName)
        }
        if (datas.isSave) {
          next()
          return
        }

        if (to.name === 'DealerInfoNewArchive') {
          // 阻止返回
          proxy.$dialog
            .confirm({
              title: '当前编辑数据未保存，是否确认退出？',
              theme: 'round-button',
              confirmButtonText: '确认',
              cancelButtonText: '取消',
              showCancelButton: true,
              closeOnPopstate: false
            })
            .then(() => {
              next()
            })
            .catch(() => {
              next(false)
            })
          return
        }
        next()
      })

      const date = new Date()
      const sDate = new Date().setMonth(date.getMonth() - 1)
      const eDate = new Date().setDate(date.getDate() + 1)
      datas.minDate = new Date(sDate)
      datas.maxDate = new Date(eDate)

      return {
        ...toRefs(datas),
        onSearchOffice,
        onSearchCustomerManager,
        onCreate
      }
    }
  }
</script>
<style lang="less" scoped></style>
